<!--
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-02-28 15:46:29
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-09-09 13:42:48
 * @FilePath: /XMate-h5/src/views/minutes/components/editParticipantInfo/customerListView.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 新增客户列表结构 -->
  <div class="flex flex-col h-full p-2">
    <div class="flex flex-row justify-between items-center">
      <van-search
        round
        class="flex-auto"
        v-model="searchValue"
        placeholder="请输入搜索关键词"
      />
      <div class="text-yxt-blue text-[14px]" @click="onClickCreate">新建</div>
    </div>

    <div class="flex-auto h-[300px] overflow-y-auto">
      <template v-if="cp_customerList.length > 0">
        <van-cell
          v-for="(customer, customerIndex) in cp_customerList"
          :key="customer.id"
          @click="onSelectCustomer(customer)"
        >
          <div class="flex flex-row items-center justify-between px-5">
            <div class="flex flex-row items-center">
              <div class="mr-3">
                <van-checkbox v-model="customer.selected"></van-checkbox>
              </div>
              <div class="flex flex-col items-start">
                <h2 class="text-[#262626] text-[16px]">{{ customer.name }}</h2>
                <span class="flex flex-row items-center flex-wrap">
                  <template
                    v-for="(customer, index) in cp_customerDesList[customerIndex]"
                  >
                    <span
                      :class="`text-[12px] mr-1 text-left`"
                      :style="{
                        color: customer.color,
                      }"
                      >{{ customer.value }}
                      {{
                        index === cp_customerDesList[customerIndex].length - 1 ? "" : "| "
                      }}</span
                    >
                  </template>
                </span>
                <p class="text-[12px] text-left" v-if="needFix(customer)">
                  该客户发言人部分信息缺失，请先编辑补充
                </p>
              </div>
            </div>
            <div class="flex flex-row items-center gap-2">
              <van-icon name="edit" @click="onEditCustomer(customer)" />
              <!-- <van-icon name="delete-o" @click="onDeleteCustomer(customer)" /> -->
            </div>
          </div>
        </van-cell>
      </template>
      <van-empty v-else description="暂无数据" />
    </div>

    <!-- 添加确认按钮 -->
    <div class="flex w-full items-center justify-center mt-2">
      <van-button type="primary" size="large" round @click="onConfirm">确认</van-button>
    </div>

    <van-popup
      v-model:show="showCustomerForm"
      teleport="#minutesPage"
      :lock-scroll="false"
      class="z-index-999"
      round
      position="bottom"
      :style="{ height: '90%' }"
    >
      <customerFormView @confirm="onConfirmCreateCustomer" />
    </van-popup>

    <van-popup
      v-model:show="showEditForm"
      teleport="#minutesPage"
      :lock-scroll="false"
      class="z-index-999"
      round
      position="bottom"
      :style="{ height: '90%' }"
    >
      <customerFormView
        v-if="showEditForm"
        title="修改内部参会人"
        :is-edit-model="true"
        :default-info="currentEditInfo"
        @confirm="onConfirmChangeCustomer"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapActions, mapState } from "pinia";
import { useMinutesStore } from "@/store";
import customerFormView from "./customerFormView.vue";
import {
  addCustomerRole,
  changeCustomerRole,
  getCustomerContactApi,
  deleteCustomerRole,
} from "@/services/minutes/lateAttender";
import {
  showFailToast,
  showLoadingToast,
  closeToast,
  showToast,
  showConfirmDialog,
} from "vant";

export default {
  data() {
    return {
      customerList: [],
      selectedCustomer: null,
      showCustomerForm: false,
      showEditForm: false,
      currentEditInfo: null,
      searchValue: "",
    };
  },

  props: {
    labelParticipantInfo: {
      type: Object,
    },
  },

  emits: ["confirmCreateCustomer", "selectCustomer"],

  components: {
    customerFormView,
  },

  methods: {
    onClickCreate() {
      this.showCustomerForm = true;
    },

    onEditCustomer(customer) {
      this.currentEditInfo = customer;
      this.showEditForm = true;
    },

    onDeleteCustomer(customer) {
      showConfirmDialog({
        title: "提示",
        message: "确定删除该客户吗？",
      }).then(() => {
        this.deleteCustomer(customer);
      });
    },

    async deleteCustomer(customer) {
      const { id, customerId } = customer;
      if (!id || !customerId) {
        showFailToast("数据异常,无法删除");
        return;
      }
      showLoadingToast(true);
      await deleteCustomerRole(id, customerId);
      await this.getCustomerContact();
      closeToast();
    },

    async onConfirmCreateCustomer(parameter) {
      this.showCustomerForm = false;
      parameter.ui = this.ui;
      showLoadingToast(true);
      const response = await addCustomerRole(this.confId, parameter);
      await this.getCustomerContact();
      if (response.code !== 0) {
        showFailToast(response.message);
        return;
      }
      closeToast();
    },

    async onConfirmChangeCustomer(parameter) {
      this.showEditForm = false;
      parameter.ui = this.ui;
      showLoadingToast(true);
      const roleId = this.currentEditInfo.id;
      const response = await changeCustomerRole(this.confId, roleId, parameter);
      await this.getCustomerContact();
      if (response.code !== 0) {
        showFailToast(response.message);
        return;
      }
      closeToast();
    },

    onSelectCustomer(customer) {
      this.customerList.forEach((item) => {
        item.selected = false;
      });
      customer.selected = true;
      this.selectedCustomer = customer;
    },

    async getCustomerContact() {
      console.log("getCustomerContact: ", this.confId);
      const res = await getCustomerContactApi(this.confId);
      if (res.code !== 0) {
        showToast("获取客户联系人失败"); // 处理异常情况
        return;
      }
      if (!res.data || res.data.length === 0) {
        // showToast("没有客户数据"); // 处理空数据情况
        return;
      }
      this.customerList = res.data;
      console.log("getCustomerContact: ", res);
    },

    onConfirm() {
      if (!this.selectedCustomer) {
        showToast("请先选择一个客户"); // 确认按钮的处理
        return;
      }
      // 处理确认逻辑
      console.log("确认选择的客户:", this.selectedCustomer);
      // 这里可以添加进一步的处理逻辑

      const { name, id, formData } = this.selectedCustomer;
      const parameter = {
        id,
        name,
      };
      parameter.formData = formData;
      this.$emit("selectCustomer", parameter);
    },

    getCustomerStatus(customer) {
      let formData = customer.formData || {};
      let fieldValues = formData.fieldValues || [];
      let statusArray = [];
      for (const outerFiled of this.cp_outerFiledTemple) {
        const obj = fieldValues.find((v) => v.fieldId === outerFiled.id) || {};
        const { fieldName } = outerFiled;
        const { fieldValue = "-" } = obj;
        const isRequired = outerFiled?.isRequired === 1;
        statusArray.push({
          color: isRequired && fieldValue === "-" ? "#fa0707" : "#999",
          value: fieldName + ":" + fieldValue,
        });
      }
      if (statusArray.length > 11) {
        statusArray = statusArray.slice(0, 11);
        statusArray.push({
          color: "#999",
          value: " ......",
        });
      }
      return statusArray;
    },

    needFix(customer) {
      let formData = customer.formData || {};
      let fieldValues = formData.fieldValues || [];
      for (const outerFiled of this.cp_outerFiledTemple) {
        const obj = fieldValues.find((v) => v.fieldId === outerFiled.id) || {};
        const { fieldValue = "-" } = obj;
        const isRequired = outerFiled?.isRequired === 1;
        if (isRequired && fieldValue === "-") {
          return true;
        }
      }
      return false;
    },

    getData() {
      this.getCustomerContact();
    },
  },

  mounted() {
    this.getData();
  },

  computed: {
    ...mapState(useMinutesStore, {
      isSalesMeet: "isSalesMeet",
      confId: "conferenceId",
      meetInfo: "getMeetInfo",
      userInfoList: "getUpdatedAsrUserList",
      outerFiledTemple: "outerFiledPartner",
    }),

    cp_outerFiledTemple() {
      return this.outerFiledTemple.filter((field) => {
        return field.fieldStatus !== 0;
      });
    },

    cp_customerList() {
      if (this.searchValue === "") {
        return this.customerList;
      }
      return this.customerList.filter((customer) => {
        console.log("customer: ", customer, this.searchValue);
        return customer.name.includes(this.searchValue); // 根据姓名筛选
      });
    },

    cp_customerDesList() {
      let array = [];
      for (const arrayElement of this.cp_customerList) {
        array.push(this.getCustomerStatus(arrayElement));
      }
      return array;
    },

    ui() {
      return this.labelParticipantInfo.uid;
    },
  },
};
</script>

<style lang="less" scoped>
.customer-list {
  list-style-type: none; /* 去掉默认列表样式 */
  padding: 0; /* 去掉内边距 */
  margin: 0; /* 去掉外边距 */
}

.customer-item {
  padding: 10px; /* 每个客户项的内边距 */
  border-bottom: 1px solid #ccc; /* 底部边框 */
  cursor: pointer; /* 鼠标悬停时显示为指针 */
  display: flex; /* 使用flex布局 */
  justify-content: space-between; /* 两端对齐 */
  align-items: center; /* 垂直居中 */
}

.customer-item:hover {
  background-color: #f0f0f0; /* 悬停时的背景色 */
}

.customer-info {
  display: flex; /* 使用flex布局 */
  justify-content: space-between; /* 两端对齐 */
  width: 100%; /* 使信息占满整个宽度 */
}

.customer-name {
  font-weight: bold; /* 客户名称加粗 */
}

.customer-status {
  color: #888; /* 状态文字颜色 */
}
</style>
